package com.example.administrator.myapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public abstract class BaseSurfaceView extends SurfaceView implements
        SurfaceHolder.Callback, Runnable
{
    private Paint mPaint;
    private SurfaceHolder mHolder;
    private Thread mThread;
    private boolean mIsRun = true;

    // 构造方法
    public BaseSurfaceView(Context context)
    {
        super(context);
        init();
    }

    public BaseSurfaceView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init();
    }

    private void init()
    {
        //笔
        mPaint = new Paint();
        //拿到控制器
        mHolder = getHolder();
        //回调事件
        mHolder.addCallback(this);
        //线程
        mThread = new Thread(this);

    }

    // 线程的运行方法
    @Override
    public void run()
    {
        while (mIsRun)
        {
            //修改数据
            update();
            //绘制
            paint();

            try
            {
                Thread.sleep(25);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }

    //数据
    private void update()
    {
        onUpdate();
    }

    //业务方法由子类进行重写
    protected abstract void onUpdate();

    //绘制
    private void paint()
    {
        Canvas canvas = null;
        try
        {
            //锁定画布
            canvas = mHolder.lockCanvas();
            if(canvas!=null)
            {
                //将画布涂黑
                canvas.drawColor(Color.WHITE);
                //绘制数据
                onPaint(canvas, mPaint);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if(canvas!=null)
            {
                //解锁画布并且提交数据
                mHolder.unlockCanvasAndPost(canvas);
            }
        }
    }

    //绘制的业务由子类实现
    protected abstract void onPaint(Canvas canvas,Paint paint);



    // 当Surface创建成功后
    @Override
    public void surfaceCreated(SurfaceHolder holder)
    {
        mThread.start();
    }

    // 当Surface发生改变时
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height)
    {
    }

    // 当Surface销毁时
    @Override
    public void surfaceDestroyed(SurfaceHolder holder)
    {
        mIsRun = false;
    }

}
